package com.zkzx.operation.api.service.area;

import com.zkzx.common.area.AreaVO;
import com.zkzx.common.exception.BaseException;
import com.zkzx.operation.api.mapper.AreaMapper;
import com.zkzx.operation.api.mapper.entity.Area;
import com.zkzx.operation.api.mapper.entity.AreaExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AreaService {

    @Resource
    private AreaMapper areaMapper;

    public List<AreaVO> getArea(Integer pid, String level) {
        AreaExample example = new AreaExample();
        example.createCriteria().andPidEqualTo(pid).andLevelEqualTo(level);
        return getAreaVOS(example);
    }

    public List<AreaVO> getLikeAreaName(String name) {
        AreaExample example = new AreaExample();
        example.createCriteria().andNameLike("%"+name+"%");
        return getAreaVOS(example);
    }

    private List<AreaVO> getAreaVOS(AreaExample example) {
        List<Area> areaList = areaMapper.selectByExample(example);

        if(areaList.isEmpty()){
            throw new BaseException(HttpStatus.SC_BAD_REQUEST, "查询结果为空");
        }

        return areaList.stream().map(area ->
                AreaVO.builder().id(area.getId()).pid(area.getPid()).name(area.getName())
                        .level(area.getLevel()).location(area.getLocation()).build()
        ).collect(Collectors.toList());
    }

    public List<Area> getAreaAll() {
        AreaExample example = new AreaExample();
        List<Area> areaList = areaMapper.selectByExample(example);

        if(areaList.isEmpty()){
            throw new BaseException(HttpStatus.SC_BAD_REQUEST, "查询结果为空");
        }
        return  areaList;
    }

    public void updateArea(Area area){
        areaMapper.updateByPrimaryKeySelective(area);
    }


}
